package cn.wjc.demo.part.three.seata.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * 请求时发送全局事务ID
 */
@Slf4j
//@Component
public class FeignSeataRequestInterceptor implements RequestInterceptor {

    /**
     * Feign请求发送时执行的方法
     * @param requestTemplate 请求方法
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            log.info("这里是FeignSeataRequestInterceptor");
            // 设置全局事务ID
            setXid(requestTemplate);
        } catch (Exception e) {
            log.error("FeignSeataRequestInterceptor exception:", e);
        }
    }

    private void setXid(RequestTemplate requestTemplate) {
        String xid = RootContext.getXID();
        if (StringUtils.hasText(xid)) {
            requestTemplate.header(RootContext.KEY_XID, xid);
        }
    }
}
